package com.rpay.admin.controller.account;

import com.rpay.admin.controller.base.BaseController;
import com.rpay.admin.param.account.UpdateAccount;
import com.rpay.common.dto.account.AccountDTO;
import com.rpay.common.dto.account.AccountQueryDTO;
import com.rpay.common.dto.user.UserRippleDTO;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.exception.UserException;
import com.rpay.common.util.DateUtil;
import com.rpay.common.util.excel.ExcelData;
import com.rpay.common.util.excel.ExportExcelUtils;
import com.rpay.common.vo.PcsResult;
import com.rpay.service.account.IAccountService;
import com.rpay.service.user.IUserIncomeService;
import com.rpay.service.user.IUserRippleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * @author XXX
 * @mail XXX@hotmail.com
 * @date 2018/5/14
 * @Description:
 */
@RestController
@RequestMapping(value = "api/account")
@Validated
public class AccountController extends BaseController {
    @Autowired
    private IAccountService iAccountService;
    @Autowired
    private IUserRippleService userRippleService;

    @Autowired
    private IUserIncomeService iUserIncomeService;

    @GetMapping(value = "")
    public PcsResult list(
            @RequestParam(name = "page", defaultValue = "1") Integer page,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "startTime", defaultValue = "") String startTime,
            @RequestParam(name = "endTime", defaultValue = "") String endTime,
            @RequestParam(name = "keyword", defaultValue = "") String keyword,
            @RequestParam(name = "level", defaultValue = "") Integer level
    ) {
        AccountQueryDTO query = new AccountQueryDTO();
        query.setStartTime(startTime.length() == 0 ? null : startTime);
        query.setEndTime(endTime.length() == 0 ? null : endTime);
        query.setPage((page - 1) * pageSize);
        query.setPageSize(pageSize);
        query.setKeyword(keyword);
        query.setLevel(level);
        AccountQueryDTO data = iAccountService.list(query, page, pageSize);
        return PcsResult.build(data);
    }

    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    public void excel(
            HttpServletResponse response,
            @RequestParam(name = "page", defaultValue = "1") Integer page,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "startTime", defaultValue = "") String startTime,
            @RequestParam(name = "endTime", defaultValue = "") String endTime,
            @RequestParam(name = "keyword", defaultValue = "") String keyword,
            @RequestParam(name = "level", defaultValue = "") Integer level
    ) throws Exception {
        AccountQueryDTO query = new AccountQueryDTO();
        query.setStartTime(startTime.length() == 0 ? null : startTime);
        query.setEndTime(endTime.length() == 0 ? null : endTime);
        query.setPage((page - 1) * pageSize);
        query.setPageSize(pageSize);
        query.setKeyword(keyword);
        query.setLevel(level);
        AccountQueryDTO listData = iAccountService.list(query, page, pageSize);
        List<AccountDTO> accountDTOList = listData.getList();
        List<List<Object>> rows = new ArrayList();
        ExcelData data = new ExcelData();
        data.setName("用户数据");
        List<String> titles = new ArrayList();
        titles.add("用户Id");
        titles.add("用户名称");
        titles.add("用户等级");
        titles.add("用户邮箱");
        titles.add("用户手机号码");
//        titles.add("用户身份证号");
        titles.add("瑞波钱包地址");
        titles.add("瑞波钱包二维码");
        titles.add("rpay钱包地址");
        titles.add("rpay钱包二维码");
        titles.add("用户分享码");
        titles.add("推荐人Id");
        titles.add("用户状态");
        titles.add("用户注册时间");
        data.setTitles(titles);
        if (accountDTOList != null && accountDTOList.size() > 0) {
            for (AccountDTO accountDTO : accountDTOList) {
                List<Object> row = new ArrayList();
                row.add(accountDTO.getId());
                row.add(accountDTO.getName());
                row.add(accountDTO.getLevel());
                row.add(accountDTO.getEmail());
                row.add(accountDTO.getPhone());
//                row.add(accountDTO.getIdcard());
                row.add(accountDTO.getRippleWalletAddr());
                row.add(accountDTO.getRippleWalletQrcode());
                row.add(accountDTO.getRpayWalletAddr());
                row.add(accountDTO.getRpayWalletQrcode());
                row.add(accountDTO.getShareCode());
                row.add(accountDTO.getParentId());
                row.add((accountDTO.getStatus().equals("VALID")) ? "有效" : ((accountDTO.getStatus().equals("INVALID")) ? "无效" : "不允许登录"));
                row.add(DateUtil.formatDateTime(accountDTO.getCreateTime()));
                rows.add(row);
            }
        }
        data.setRows(rows);
        ExportExcelUtils.exportExcel(response, "注册用户数据.xlsx", data);
    }

    @PatchMapping(value = "/update/{id}")
    public PcsResult update(@Validated @RequestBody UpdateAccount updateAccount, @PathVariable("id") Integer id) {
        if (updateAccount.getLevel() != null && (updateAccount.getLevel() < 0 || updateAccount.getLevel() > 6)) {
            throw new UserException(PcsResultCode.BUSINESS_LEVEL_ERROR);
        }
        AccountDTO accountDTO = new AccountDTO();
        accountDTO.setId(id);
        accountDTO.setStatus(updateAccount.getStatus());
        accountDTO.setName(updateAccount.getName());
        accountDTO.setPhone(updateAccount.getPhone());
        accountDTO.setRippleWalletAddr(updateAccount.getRippleWalletAddr());
        accountDTO.setRpayWalletAddr(updateAccount.getRpayWalletAddr());
        accountDTO.setLevel(updateAccount.getLevel());
        iAccountService.patch(accountDTO);
        return new PcsResult();
    }

    /**
     * 用户购买合约列表
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "ripple/list/{userId}")
    public PcsResult rippleList(@PathVariable Integer userId) {
        List<UserRippleDTO> list = userRippleService.listUserRipple(userId);
        return new PcsResult(list);
    }

    /**
     * 指数统计
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "/statistics/{userId}")
    public PcsResult incomeStatistics(@PathVariable Integer userId) {
        return PcsResult.build(iUserIncomeService.statistics(userId));
    }

    /**
     * 指数明细
     *
     * @param userId
     * @param beginDate
     * @param endDate
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping(value = "income/list")
    public PcsResult list(@RequestParam @NotNull(message = "用户id不能为空") Integer userId, String beginDate, String endDate, Integer pageIndex, Integer pageSize) {
        pageIndex = getPageIndex(pageIndex);
        pageSize = getPageSize(pageSize);
        return PcsResult.build(iUserIncomeService.listUserIncome(userId, beginDate, endDate, pageIndex, pageSize));
    }
}
